/*
 * @Author: AiLjx
 * @Date: 2022-06-11 15:26:39
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-07-01 22:32:28
 */
import { Routes, Route, Link, BrowserRouter } from "react-router-dom";

// lazy配合Suspense实现组件懒加载
// 导入必要组件
// 在 App 组件中，导入 Suspense 组件
// 导入 lazy 函数，并修改为懒加载方式导入路由组件
import { lazy, Suspense } from "react";
// 按需导入路由组件(懒加载)
const Home = lazy(() => import("./views/Home"));
const About = lazy(() => import("./views/About"));

function App() {
    return (
        <BrowserRouter>
            <Link to='/'>首页 </Link>
            <Link to='/about'>关于 </Link>

            {/*  路由懒加载方法一：外部lazy导入组件，再使用 Suspense 组件包裹Routes */}
            {/* <Suspense
                // 为 Suspense 组件提供 fallback 属性，指定 loading 占位内容
                fallback={
                    <div
                        style={{
                            textAlign: "center",
                            marginTop: 200,
                        }}>
                        loading...
                    </div>
                }>
                <Routes>
                    <Route path='/' element={<Home />}></Route>
                    <Route path='/about' element={<About />}></Route>
                </Routes>
            </Suspense> */}

            {/* 路由懒加载方法二：使用封装的组件懒加载 */}
            <Routes>
                <Route path='/' element={LazyLoad("Home")}></Route>
                <Route path='/about' element={LazyLoad("About")}></Route>
            </Routes>
        </BrowserRouter>
    );
}

export default App;

// 封装组件懒加载
const LazyLoad = (path) => {
    // import中必须要有一个固定的前缀，直接import(path)不行
    const Comp = lazy(() => import(`./views/${path}`));
    return (
        <Suspense
            fallback={
                <div
                    style={{
                        textAlign: "center",
                        marginTop: 200,
                    }}>
                    loading...
                </div>
            }>
            <Comp></Comp>
        </Suspense>
    );
};
